<template src="./template.html"></template>
<script>
/* global _ */
import checkForm from 'mixins/checkform'
import { FUN_IDS_OPTIONS } from 'common/consts.js'
import { validateCourseName } from 'utils/ui-utils'
import { PRACTICE_LIST, PresetsForm } from './consts'
import { addLesson, getLessonById, updateLesson } from '../models'
import ExampleDialog from './example-dialog.vue'

export default {
  components: { ExampleDialog },
  mixins: [checkForm],
  data() {
    return {
      FUN_IDS_OPTIONS,
      PRACTICE_LIST,
      basicForm: _.cloneDeep(PresetsForm),
      rules: {
        lessonName: [{ required: true, message: '请输入课时名称', trigger: 'change' },
          { validator: validateCourseName, trigger: 'blur' }],
        salesLanguage: [
          { required: true, message: '请输入话术内容', trigger: 'change' },
          { validator: this.$validSalesLanguage, trigger: 'blur' }
        ],
        practiceProject: { required: true, message: '请选择练习项目', trigger: 'change' },
        keywords: { required: true, message: '请输入关键词', trigger: 'change' },
        passingScore: { required: true, message: '请输入通关及格分', trigger: 'change' },
      },
      exampleVisible: false,
      practiceProject: [],
    }
  },
  computed: {
    userInfo() {
      const info = this.$store.state.user.userInfo
      console.log('userInfo:', info)
      return info
    },
    courseId() {
      return this.$route.params.courseId
    },
    lessonId() {
      return this.$route.params.id
    },
    isEdit() {
      return this.$route.name === 'curriculum.manager.edit-period'
    }
  },
  methods: {
    $validSalesLanguage(rule, value, callback) {
      let isNull = false
      for (const k in this.basicForm.salesLanguage) {
        if (!this.basicForm.salesLanguage[k].trim()) {
          isNull = true
        }
      }
      if (isNull) {
        return callback(new Error('请输入话术内容'))
      }
      callback()
    },
    handleInput(value) {
      const regex = /^(100|[1-9]?\d)(\.\d{0,1})?$/;
      if (value && !regex.test(value)) {
        this.basicForm.passingScore = value.replace(/[^\d.]/g, '')
          .replace(/(\..*)\./g, '$1')
          .replace(/^(\d+)\.?(\d*).*$/, (match, p1, p2) => {
            // 明确指定 parseInt 的进制参数为 10
            const integer = Math.min(100, parseInt(p1 || 0, 10));
            const decimal = p2 ? `.${p2.slice(0, 1)}` : '';
            return integer + decimal;
          });
      }
      // this.basicForm.passingScore = value.replace(/[^\d]/g, '');
    },
    async $saveForm() {
      if (!this.$checkForm('basicForm')) {
        return
      }
      this.isPageLoading = true
      const params = {
        ...this.basicForm,
        courseId: this.courseId,
        passingScore: { 102: this.basicForm.passingScore },
        practiceProject: this.basicForm.practiceProject && this.basicForm.practiceProject.join('、')
      }
      let fun = addLesson
      if (this.lessonId) {
        fun = updateLesson
        params.id = this.lessonId
      }
      try {
        await fun(params)
        this.isPageLoading = false
        this.$refs['basicForm'].resetFields()
        this.$message.success('保存信息成功')
        this.$router.go(-1)
      } catch (err) {
        this.isPageLoading = false
        this.$message.error(err.message || err.message || '保存信息出错')
      }
    },
    async $getLessonById() {
      this.isPageLoading = true
      const params = {
        id: this.lessonId
      }
      try {
        const { data } = await getLessonById(params)
        for (const k in this.basicForm) {
          this.basicForm[k] = data[k]
        }
        this.basicForm.salesLanguage = data.salesLanguageMap
        this.basicForm.passingScore = data.passingScoreMap[102]
        this.basicForm.practiceProject = data.practiceProject.split(',')
        console.log(this.basicForm)
        this.isPageLoading = false
      } catch (err) {
        this.isPageLoading = false
        this.$message.error(err.message || '获取信息出错')
      }
    }
  },
  mounted() {
    if (this.lessonId) {
      this.$getLessonById()
    }
  }
}
</script>
